package com.childenglish.service;

import com.childenglish.entity.PictureBook;
import com.childenglish.entity.StudentReadingProgress;
import com.childenglish.entity.SysClass;
import com.childenglish.entity.SysStudentClass;
import com.childenglish.mapper.PictureBookMapper;
import com.childenglish.mapper.StudentReadingProgressMapper;
import com.childenglish.mapper.SysClassMapper;
import com.childenglish.mapper.SysStudentClassMapper;
import com.childenglish.mapper.SysUserMapper;
import com.childenglish.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PictureBookService {

    @Autowired
    private PictureBookMapper pictureBookMapper;

    @Autowired
    private StudentReadingProgressMapper readingProgressMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysStudentClassMapper sysStudentClassMapper;

    @Autowired
    private SysClassMapper sysClassMapper;

    /**
     * 根据学生ID推荐绘本
     * 推荐逻辑：
     * 1. 根据学生的班级信息获取年龄范围和年级级别
     * 2. 根据班级类别推荐相应难度的绘本
     * 3. 优先推荐简单难度的绘本，然后中等，最后困难
     */
    public List<Map<String, Object>> getRecommendedBooks(Long studentId) {
        List<Map<String, Object>> result = new ArrayList<>();

        try {
            // 获取学生信息
            SysUser student = sysUserMapper.findById(studentId);
            if (student == null || !"02".equals(student.getUserType())) {
                return result;
            }

            // 获取学生的班级信息
            List<SysStudentClass> studentClasses = sysStudentClassMapper.findByStudentId(studentId);
            if (studentClasses == null || studentClasses.isEmpty()) {
                // 如果没有班级信息，返回所有简单难度的绘本
                return getAllBooksByDifficulty("easy");
            }

            SysStudentClass studentClass = studentClasses.get(0);
            SysClass classInfo = sysClassMapper.findById(studentClass.getClassId());
            if (classInfo == null) {
                return getAllBooksByDifficulty("easy");
            }

            // 解析年龄范围
            Integer age = parseAgeFromRange(classInfo.getAgeRange());
            String gradeLevel = classInfo.getGradeLevel();
            String classCategory = classInfo.getClassCategory();

            // 根据年龄、年级级别和班级类别推荐绘本
            List<PictureBook> recommendedBooks = pictureBookMapper.findRecommendedBooks(
                    age, gradeLevel, classCategory);

            // 获取学生的阅读进度
            Map<Long, StudentReadingProgress> progressMap = new HashMap<>();
            List<StudentReadingProgress> progressList = readingProgressMapper.findByStudentId(studentId);
            if (progressList != null) {
                progressMap = progressList.stream()
                        .collect(Collectors.toMap(StudentReadingProgress::getBookId, p -> p));
            }

            // 转换为前端需要的格式，并添加进度信息
            for (PictureBook book : recommendedBooks) {
                Map<String, Object> bookMap = convertToMap(book);
                
                // 添加阅读进度
                StudentReadingProgress progress = progressMap.get(book.getBookId());
                if (progress != null) {
                    bookMap.put("progress", progress.getProgress());
                } else {
                    bookMap.put("progress", 0);
                }

                result.add(bookMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
            // 出错时返回空列表
        }

        return result;
    }

    /**
     * 根据难度获取所有绘本
     */
    private List<Map<String, Object>> getAllBooksByDifficulty(String difficulty) {
        List<PictureBook> books = pictureBookMapper.findByDifficulty(difficulty);
        return books.stream()
                .map(this::convertToMap)
                .collect(Collectors.toList());
    }

    /**
     * 解析年龄范围，返回平均年龄
     */
    private Integer parseAgeFromRange(String ageRange) {
        if (ageRange == null || ageRange.isEmpty()) {
            return 5; // 默认年龄
        }

        try {
            // 解析 "3-4岁" 格式
            String range = ageRange.replace("岁", "").trim();
            String[] parts = range.split("-");
            if (parts.length == 2) {
                int minAge = Integer.parseInt(parts[0].trim());
                int maxAge = Integer.parseInt(parts[1].trim());
                return (minAge + maxAge) / 2;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 5; // 默认年龄
    }

    /**
     * 将PictureBook转换为Map格式（前端需要的格式）
     */
    private Map<String, Object> convertToMap(PictureBook book) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", book.getBookId());
        map.put("title", book.getTitle());
        map.put("cover", book.getCoverUrl());
        map.put("difficulty", book.getDifficulty());
        map.put("progress", 0); // 默认进度为0

        // 解析content字段（JSON格式）为pages数组
        if (book.getContent() != null && !book.getContent().isEmpty()) {
            try {
                // 这里简化处理，实际应该使用JSON解析库
                // 暂时返回空数组，前端可以处理
                map.put("pages", new ArrayList<>());
            } catch (Exception e) {
                map.put("pages", new ArrayList<>());
            }
        } else {
            map.put("pages", new ArrayList<>());
        }

        return map;
    }

    /**
     * 获取绘本详情
     */
    public Map<String, Object> getBookDetail(Long bookId) {
        PictureBook book = pictureBookMapper.findById(bookId);
        if (book == null) {
            return null;
        }

        Map<String, Object> map = convertToMap(book);
        map.put("author", book.getAuthor());
        map.put("description", book.getDescription());
        map.put("totalPages", book.getTotalPages());

        // 解析content为pages
        if (book.getContent() != null && !book.getContent().isEmpty()) {
            try {
                // 这里应该使用JSON解析库解析content
                // 暂时返回空数组
                map.put("pages", new ArrayList<>());
            } catch (Exception e) {
                map.put("pages", new ArrayList<>());
            }
        } else {
            map.put("pages", new ArrayList<>());
        }

        return map;
    }

    /**
     * 更新阅读进度
     */
    public void updateReadingProgress(Long studentId, Long bookId, Integer currentPage, Integer totalPages) {
        try {
            int progress = totalPages > 0 ? (int) Math.round((currentPage * 100.0) / totalPages) : 0;
            progress = Math.min(progress, 100);

            StudentReadingProgress readingProgress = readingProgressMapper.findByStudentAndBook(studentId, bookId);
            
            if (readingProgress == null) {
                // 创建新记录
                readingProgress = new StudentReadingProgress();
                readingProgress.setStudentId(studentId);
                readingProgress.setBookId(bookId);
                readingProgress.setProgress(progress);
                readingProgress.setCurrentPage(currentPage);
                readingProgress.setReadCount(1);
                readingProgress.setLastReadTime(LocalDateTime.now());
                readingProgress.setCreateTime(LocalDateTime.now());
                readingProgress.setUpdateTime(LocalDateTime.now());
            } else {
                // 更新记录
                readingProgress.setProgress(progress);
                readingProgress.setCurrentPage(currentPage);
                readingProgress.setReadCount(readingProgress.getReadCount() + 1);
                readingProgress.setLastReadTime(LocalDateTime.now());
                readingProgress.setUpdateTime(LocalDateTime.now());
            }

            readingProgressMapper.insertOrUpdate(readingProgress);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

